import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router';
import type { App, Plugin } from 'vue';
import dayjs from "dayjs";

import { unref } from 'vue';
import { isObject } from '/@/utils/is';
import { dateUtil } from '/@/utils/dateUtil';

export const noop = () => {};

/**
 * @description:  Set ui mount node
 */
export function getPopupContainer(node?: HTMLElement): HTMLElement {
  return (node?.parentNode as HTMLElement) ?? document.body;
}

/**
 * Add the object as a parameter to the URL
 * @param baseUrl url
 * @param obj
 * @returns {string}
 * eg:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
export function setObjToUrlParams(baseUrl: string, obj: any): string {
  let parameters = '';
  for (const key in obj) {
    parameters += key + '=' + encodeURIComponent(obj[key]) + '&';
  }
  parameters = parameters.replace(/&$/, '');
  return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters;
}

export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
  let key: string;
  for (key in target) {
    src[key] = isObject(src[key]) ? deepMerge(src[key], target[key]) : (src[key] = target[key]);
  }
  return src;
}

export function openWindow(
  url: string,
  opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean },
) {
  const { target = '__blank', noopener = true, noreferrer = true } = opt || {};
  const feature: string[] = [];

  noopener && feature.push('noopener=yes');
  noreferrer && feature.push('noreferrer=yes');

  window.open(url, target, feature.join(','));
}

// dynamic use hook props
export function getDynamicProps<T, U>(props: T): Partial<U> {
  const ret: Recordable = {};

  Object.keys(props).map((key) => {
    ret[key] = unref((props as Recordable)[key]);
  });

  return ret as Partial<U>;
}

export function getRawRoute(route: RouteLocationNormalized): RouteLocationNormalized {
  if (!route) return route;
  const { matched, ...opt } = route;
  return {
    ...opt,
    matched: (matched
      ? matched.map((item) => ({
          meta: item.meta,
          name: item.name,
          path: item.path,
        }))
      : undefined) as RouteRecordNormalized[],
  };
}

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any;
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, component);
    if (alias) {
      app.config.globalProperties[alias] = component;
    }
  };
  return component as T & Plugin;
};
// 验证是否外部地址
export function isExternal(path: string) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

// 复制文本
export function copy(text: string) {
  const input = document.createElement('textarea');
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
}

// 返回时间范围
// time: 1：今天 2：近三天 3：近一周 4：近半月 5：近一个月
export function getTimes(time: number) {
  let startTime = ''
  let endTime = ''
  let today = new Date()
  switch (time) {
    case 1:
      startTime = dateUtil(new Date()).format('YYYY-MM-DD')
      endTime = dateUtil(new Date()).format('YYYY-MM-DD')
      break;
    case 2:
      endTime = dateUtil(today).format('YYYY-MM-DD')
      startTime = dateUtil(today.setDate(today.getDate() - 2)).format('YYYY-MM-DD')
      break;
    case 3:
      endTime = dateUtil(today).format('YYYY-MM-DD')
      startTime = dateUtil(today.setDate(today.getDate() - 6)).format('YYYY-MM-DD')
      break;
    case 4:
      endTime = dateUtil(new Date()).format('YYYY-MM-DD')
      startTime = dateUtil(today.setDate(today.getDate() - 14)).format('YYYY-MM-DD')
      break;
    case 5:
      endTime = dateUtil(new Date()).format('YYYY-MM-DD')
      startTime = dateUtil(today.setDate(today.getDate() - 29)).format('YYYY-MM-DD')
      break;
  }
  return [startTime, endTime]
}

// 时间戳改为时间范围
export function setTimes(time: number) {
  console.log(123123, new Date(time).getDate())
  // let day = (new Date().getTime() - time) / (24 * 3600 * 1000)
  let day = new Date().getDate() - new Date(time).getDate()
  if (day === 0) {
    return '今天'
  }
  if (day >= 1 && day < 3 ) {
    return '近三天'
  }
  if (day >= 3 && day < 7 ) {
    return '近一周'
  }
  if (day >= 7 && day < 15 ) {
    return '近半月'
  }
  if (day >= 15 && day < 30 ) {
    return '近一个月'
  }
  if (day >= 30 ) {
    return '一月前'
  }
}

/**
 * 按照xxx 格式化时间
 * @param date 
 * @param formatType 
 * @returns 
 */
export const formatDate = (date : string | number = new Date().valueOf(),formatType = "YYYY-MM-DD") => {
  return dayjs(date).format(formatType)
}
